﻿using DAO;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using WebApplication.Core.Helpers;

namespace WebApplication.Core
{
    public class Deploy
    {
        public void DeployApplication(DeployObject application, string rootAppPath)
        {
            string dir = Path.GetTempPath() + application.Server.Name + "(" + application.Name + ")";
            string zipPath = GetZipPackagePath(application.Name, application.Server.Name);
            string commandFile = rootAppPath + "runDeployCommand.txt";

            string cmd = DeployHelper.GetConfiguredDeployCommand(commandFile, GetSetParametersFilePath(application.Name, application.Server.Name
                , application.Customization.CustomizationXml)
                , application.Server.RemoteHostName
                , application.Server.ServerLogin
                , application.Server.ServerPassword
                , zipPath);
            CmdHelper.RunCmd(GetBat(application.Name, application.Server.Name, cmd), false);
        }

        private string GetBat(string applicationName, string serverName, string cmd)
        {
            string batchFolder = Path.GetTempPath() + serverName + "" + applicationName + "Batch";
            string batchName = serverName + "" + applicationName + "batch.bat";
            string path = Path.Combine(batchFolder, batchName);
            if (!Directory.Exists(batchFolder))
                Directory.CreateDirectory(batchFolder);
            if (File.Exists(path))
                File.Delete(path);
            File.WriteAllText(path, cmd);
            return path;
        }

        public string GetZipPackagePath(string appName, string serverName)
        {
            string dir = Path.GetTempPath() + serverName + "(" + appName + ")";
            string zip = Directory.GetFiles(dir, "*zip", SearchOption.AllDirectories)[0];
            return zip;
        }

        public string GetSetParametersFilePath(string applicationName, string serverName, string fileContent)
        {
            string setParametersPath = Path.GetTempPath() + serverName + "(" + applicationName + ")";
            string setParametersName = serverName + "(" + applicationName + ")SetParameters.xml";
            string path = Path.Combine(setParametersPath, setParametersName);
            if (File.Exists(path))
                File.Delete(path);
            File.WriteAllText(path, fileContent);
            return path;
        }

    }
}